using System;
using System.Collections.Generic;
using System.Text;
using WCSFContrib.ECommerceCatalog.BusinessEntities;
using WCSFContrib.ECommerceCatalog.CatalogData;

namespace WCSFContrib.ECommerceCatalog.Product.Services
{
    public class CategoriesService : ICategoriesService
    {
        private CatalogDataSet _catalogDataSet;

        public CategoriesService()
            : this(CatalogRepository.Instance)
        { }

        public CategoriesService(CatalogDataSet ds)
        {
            _catalogDataSet = ds;
        }

        public ICollection<Category> AllCategories
        {
            get
            {
                ICollection<Category> categories = new List<Category>();
                foreach (CatalogDataSet.CategoryRow row in _catalogDataSet.Category.Rows)
                {
                    Category parentCategory = GetCategoryById(row.ParentCategory);
                    categories.Add(new Category(row.CategoryId, row.Code, row.Name, parentCategory));
                }
                return categories;
            }
        }

        public ICollection<Category> AllParentCategories
        {
            get
            {
                ICollection<Category> categories = new List<Category>();
                foreach (CatalogDataSet.CategoryRow row in _catalogDataSet.Category.Rows)
                {
                    Category parentCategory = GetCategoryById(row.ParentCategory);
                    if (parentCategory == null)
                        categories.Add(new Category(row.CategoryId, row.Code, row.Name, parentCategory));
                }
                return categories;
            }
        }

        public Category GetCategoryById(int categoryId)
        {
            Category parentCategory = null;
            CatalogDataSet.CategoryRow categoryRow = _catalogDataSet.Category.FindByCategoryId(categoryId);

            if (categoryRow == null)
                return null;

            parentCategory = GetCategoryById(categoryRow.ParentCategory);

            return new Category(categoryRow.CategoryId, categoryRow.Code, categoryRow.Name, parentCategory);
        }

        public ICollection<Category> GetSubCategories(int categoryId)
        {
            ICollection<Category> categories = new List<Category>();
            foreach (CatalogDataSet.CategoryRow row in _catalogDataSet.Category.Rows)
            {
                if (row.ParentCategory == categoryId)
                {
                    Category parentCategory = GetCategoryById(row.ParentCategory);
                    categories.Add(new Category(row.CategoryId, row.Code, row.Name, parentCategory));
                }
            }
            return categories;
        }
    }
}
